<?php
/**
 * Created by PhpStorm.
 * User: Hong
 * Date: 2018/3/17
 * Time: 15:15
 * Function:
 */

namespace Platform\Models\Admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Department extends Model
{
    protected $table = 'admin_departments';

    /**
     * @var array
     */
    protected $fillable = ['name','parent_id'];

    /**
     * 绑定员工表关系
     * @return BelongsToMany
     * fixme 改为一对多的关系
    public function admins() : BelongsToMany
    {
        return $this->belongsToMany(Administrator::class, 'admin_role_users', 'role_id', 'user_id');
    }
     */

    /**
     * 绑定员工表关系
     * @return HasMany
     */
    public function admins() : HasMany
    {
        return $this->hasMany(Administrator::class, 'department_id', 'id');
    }

    /**
     * 是否是超级管理员角色
     *
     * @return bool
     */
    public function isAdmin(){
        $adminstrators = config('admin.adminrole');
        return in_array($this->id, $adminstrators);
    }

    /**
     * 绑定权限表关系
     * @return BelongsToMany
     */
    public function permissions() : BelongsToMany
    {
        return $this->belongsToMany(Permission::class, 'admin_department_permissions', 'department_id', 'permission_id');
    }

    /**
     * 获取角色下的权限
     * @return array
     */
    public function getPermissions(){

        $permissions = Permission::get(['id','name','module','uri','method']);
        $department_permissions = [];
        foreach ($this->permissions as $permission) {
            foreach ($permission->toPermissions() as $method => $uri) {
                $department_permissions[$method][] = $uri;
            }
        }
        $data = Permission::makeData($permissions,$department_permissions);
        return $data;
    }
}